#pragma once
#include <sys/epoll.h>
#include "Log.hpp"
#include <errno.h>
#include <cstring>
#include <unistd.h>
#include <stdlib.h>
#include <set>
class Epoller
{
public:
    Epoller()
    {
        _epfd = epoll_create(1);
        if(_epfd < 0)
        {
            lg.LogMessage(Error, "epoll_create failed, errno:%d: %s\n", errno, strerror(errno));
            exit(epoll_create_err);
        }
    }
    void AddEvent(int fd, uint32_t events)
    {   
        _fds.insert(fd);
        struct epoll_event event;
        event.events = events;
        event.data.fd = fd;     //给用户
        int ok = epoll_ctl(_epfd, EPOLL_CTL_ADD, fd, &event);
        if(ok == -1)
        {
            lg.LogMessage(Error, "epoll_ctl add failed, errno:%d: %s\n", errno, strerror(errno));
        }
    }
    void DelEvent(int fd, uint32_t events)
    {
        _fds.erase(fd);
        struct epoll_event event;
        event.events = events;
        event.data.fd = fd;     //给用户
        int ok = epoll_ctl(_epfd, EPOLL_CTL_DEL, fd, &event);
        if(ok == -1)
        {
            lg.LogMessage(Error, "epoll_ctl del failed, errno:%d: %s\n", errno, strerror(errno));
        }
    }
    int Wait(struct epoll_event* events, int maxevents, int timeout)
    {
        return epoll_wait(_epfd, events, maxevents, timeout);
    }
    void PrintDebug()
    {
        std::cout << "关心的读事件的fd: ";
        for(auto& fd : _fds)
            if(fd != -1)
                std::cout << fd << " ";
        std::cout << std::endl;
    }
    ~Epoller()
    {
        close(_epfd);
    }
private:
    int _epfd;
    std::set<int> _fds;     //debug
};